package com.yssoft.service.sales;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.StringUtil;
import com.yssoft.common.Constants;
import com.yssoft.entity.core.TCode;
import com.yssoft.entity.core.TenterpriseLicence2;
import com.yssoft.entity.purchase.TRecipientAtt;
import com.yssoft.entity.sales.TCustomer;
import com.yssoft.entity.sales.TCustomerArea;
import com.yssoft.entity.sales.TCustomerAtt;
import com.yssoft.mapper.core.TCodeMapper;
import com.yssoft.mapper.sales.TCustomAttMapper;
import com.yssoft.mapper.sales.TCustomMapper;
import com.yssoft.mapper.sales.TDealerMapper;
import com.yssoft.utils.AppUserHelper;
import com.yssoft.utils.UploadFile;

@Service
public class DealerService {
	
	@Resource
	private TDealerMapper dealerMapper;
	@Resource
	private TCodeMapper tCodeMapper;
	
	@Resource
	private TCustomMapper tCustomMapper;
	@Resource
	private TCustomAttMapper  tCustomAttMapper;
	/**
	 * 图片上传
	 * @param mFile
	 * @return
	 */
	public Map<String, Object> compressUploadedFile(MultipartFile mFile) {
		Map<String, Object> fileNames = UploadFile.compressUploadedFile(mFile);
		return fileNames;
	}

	public List<Map<String, Object>> findPage(Integer currentPage, Integer pageSize, String name, HttpServletRequest request,Map<String, Object> requestMap) {
		Map<String, Object> param = new HashMap<>();
		/*分页整理*/
		if(currentPage!=null && pageSize!=null){
			int start = ((currentPage - 1) * pageSize);
			param.put("start",start);
			param.put("end", pageSize);
		}
		/*查询条件整理*/
		param.put("tEId",AppUserHelper.getCurrentCompanyId(request));
		param.put("deleteFlag", 0);
		param.put("type", 1);//类型：1-经销商 2-客户
		/*自定义条件整理*/
		if(requestMap.containsKey("name")  &&StringUtil.isNotEmpty(requestMap.get("name").toString())) {
			param.put("name", name);
		}
		if(requestMap.containsKey("type")  &&StringUtil.isNotEmpty(requestMap.get("type").toString())) {
			param.put("type", requestMap.get("type"));
		}
		
		/*查询经销商列表及附件信息*/
		List<Map<String, Object>> dealerList = dealerMapper.selectCustomerList(param);
		//查询地域信息
		Map<String, Object> param_area = new HashMap<>();
		List<Map<String, Object>>  areaList = dealerMapper.selectCustomArea(param_area,dealerList);
		//匹配信息
		if(dealerList!=null && areaList!=null && areaList.size()>0) {
			for(Map<String, Object> custom:dealerList) {
				String tCId=custom.get("ID").toString();
				String AREANAME="";//销售区域：</br>
				 
				for (int i = 0; i < areaList.size(); i++) {
					Map<String, Object> area=areaList.get(i);
					String a_tCId =area.get("tCId").toString();
					if(a_tCId.equals(  tCId)) {
						String  str="    "+area.get("yname")+" "+area.get("ename")+" "+area.get("sname");
						if(str.length()>30) {
							str=str.substring(0,25)+"....";
						}
						AREANAME=AREANAME+str+"</br>";
					}
					
				}
				if(StringUtils.isNoneBlank(AREANAME)) {
					//限制，最多拼凑不超过三条
					AREANAME=AREANAME.substring(0, AREANAME.lastIndexOf("</br>"));
					if(AREANAME.contains("</br>"  ) && AREANAME.split("</br>" ).length>3) {
						String[] areaNames=AREANAME.split("</br>" );
						AREANAME=areaNames[0]+"</br>"+areaNames[1]+"</br>"+areaNames[2]+"</br>....</br>";
						 
					}
					
				}
				custom.put("AREANAME", AREANAME);
			}
		}
		
		return dealerList;
	}
	
	/**
	* 
    * @Title: supplierDel
    * @Description: 批量删除
    * @param @param idArry    参数
    * @return void    返回类型
    * @throws
	 */
	public String  deleteDealer(String[] idArry) {
		String msg="0";
		//如果该经销商已经关联产生销售订单，不能删除，提示内容为“该经销商已关联产生销售订单，无法删除，请删除订单后再进行删除操作”
		int count=dealerMapper.hasBills(idArry);
		if(count==0) {
			TCustomer obj=new TCustomer();
			obj.setDeleteFlag("1");
			dealerMapper.deleteDealers(idArry,obj);
		}else {
			msg="该经销商已关联产生销售订单，无法删除，请删除订单后再进行删除操作";
		}
		
		return msg;
	}

	public Map<String, Object> findDetail(Integer id) {
		Map<String, Object> param=new HashMap<>();
		param.put("id", id);
		param.put("classify", Constants.C_LICENCE_TYPE);
		param.put("deleteFlag", "0");
		Map<String, Object>  data=new HashMap<String, Object>();
		data=dealerMapper.findDetail(id);
		//查询附件,地理信息
		List<Map<String, Object>>  attrList=dealerMapper.findAttrs(param);
		if(null!=attrList && attrList.size()>0) {
			for(Map<String, Object> img:attrList) {
				data.put("img"+img.get("type"), img);
				data.put("imgUrl"+img.get("type"), img.get("url"));
				 
			}
		}
		//查询地域信息
		Map<String, Object> param_area = new HashMap<>();
		param_area.put("tCId", id);
	 	List<Map<String, Object> > areaList=dealerMapper.selectCustomArea(param_area,null);
	 	if(null!=areaList && areaList.size()>0) {
	 		System.out.println(areaList.toString());
			data.put("area", areaList);
		}
		return data;
	}
	//String json="[{\"id\":\"110101\"},{\"id\":\"430102\"},{\"id\":\"110101\"},{\"id\":\"430102\"}]";
	/**
	 * 
	    * @Title: json2List
	    * @Description: json数组转化为list数组
	    * @param @param json
	    * @param @return    参数
	    * @return List    返回类型
	    * @throws
	 */
	private List json2List(String json) {
		List<String> list=new ArrayList<>();
		 
		JSONArray jsonArray = JSONArray.parseArray(json);
		for(int i=0;i<jsonArray.size();i++){  
			 // 遍历 jsonarray 数组，把每一个对象转成 json 对象  
			JSONObject job = jsonArray.getJSONObject(i);   
			list.add(job.get("sid")+"");
	    }  
		return new ArrayList(new TreeSet(list)); 
	}
 
	
	@Transactional(rollbackFor=Exception.class)
	public void editTCustomer(TCustomer custom, TenterpriseLicence2 tEnterpriseLicence, HttpServletRequest request, String areaJson) {
		/*获取新增经销商信息id*/
		Integer id = custom.getId();
		dealerMapper.findDetail(id);
		tCustomMapper.updateCustom(custom);
		
		/*营业执照信息,流通许可*/
		TCustomerAtt attr=new TCustomerAtt();
		attr.settCId(id);
		attr.setDeleteFlag("1");
		dealerMapper.updateCustomAttByCustomId(attr);
		
		/*营业执照信息*/
		TCustomerAtt attr1=new TCustomerAtt();
		attr1.settCId(id);
		attr1.setCreateTime(new Date());
		attr1.settEId(AppUserHelper.getCurrentCompanyId(request));
		attr1.setCreatorName(AppUserHelper.getCurrentUserName(request));
		attr1.setDeptName(AppUserHelper.getCurrentDeptName(request));
		attr1.setDeptId(AppUserHelper.getCurrentDeptId(request));
		attr1.setCreatorId(AppUserHelper.getCurrentUserId(request));
		attr1.setDeleteFlag("0");
		attr1.setType("1");//码表值-生产许可证
		attr1.setUrl(  tEnterpriseLicence.getLicenceImg() );
		attr1.settUrl( tEnterpriseLicence.getLicenceTimg()   );
		tCustomAttMapper.insertCustomerAtt(attr1);
		/*流通许可*/
		TCustomerAtt attr2=new TCustomerAtt();
		attr2.settCId(id);
		attr2.setCreateTime(new Date());
		attr2.settEId(AppUserHelper.getCurrentCompanyId(request));
		attr2.setCreatorName(AppUserHelper.getCurrentUserName(request));
		attr2.setDeptName(AppUserHelper.getCurrentDeptName(request));
		attr2.setDeptId(AppUserHelper.getCurrentDeptId(request));
		attr2.setCreatorId(AppUserHelper.getCurrentUserId(request));
		attr2.setDeleteFlag("0");
		attr2.setType("2");//码表值-营业执照
		attr2.setUrl(  tEnterpriseLicence.getLicenceImg2() );
		attr2.settUrl( tEnterpriseLicence.getLicenceTimg2()   );
		tCustomAttMapper.insertCustomerAtt(attr2);
		/*保存区域信息*/
		if(StringUtils.isNotBlank(areaJson)) {
			dealerMapper.deleteArreasByCId(id);
			dealerMapper.insertArreas(json2List(areaJson),id);
		}
		
		
	}
	@Transactional(rollbackFor=Exception.class)
	public void saveTCustomer(TCustomer custom, TenterpriseLicence2 tEnterpriseLicence, HttpServletRequest request, String areaJson) {
		
		/*信息实体补充基础数据*/
		custom.setCreateTime(new Date());
        custom.settEId(AppUserHelper.getCurrentCompanyId(request));
        custom.setCreatorName(AppUserHelper.getCurrentUserName(request));
        custom.setDeptName(AppUserHelper.getCurrentDeptName(request));
        custom.setDeptId(AppUserHelper.getCurrentDeptId(request));
        custom.setCreatorId(AppUserHelper.getCurrentUserId(request));
        custom.setType('1');//类型：1-经销商 2-客户
        custom.setDeleteFlag("0");
		/*保存供应商信息*/
        tCustomMapper.insertCustom(custom);
        
		/*获取新增经销商信息id*/
		Integer id = custom.getId();
		/*营业执照信息*/
		TCustomerAtt attr1=new TCustomerAtt();
		attr1.settCId(id);
		attr1.setCreateTime(new Date());
		attr1.settEId(AppUserHelper.getCurrentCompanyId(request));
		attr1.setCreatorName(AppUserHelper.getCurrentUserName(request));
		attr1.setDeptName(AppUserHelper.getCurrentDeptName(request));
		attr1.setDeptId(AppUserHelper.getCurrentDeptId(request));
		attr1.setCreatorId(AppUserHelper.getCurrentUserId(request));
		attr1.setDeleteFlag("0");
		attr1.setType("1");//码表值-生产许可证
		attr1.setUrl(  tEnterpriseLicence.getLicenceImg() );
		attr1.settUrl( tEnterpriseLicence.getLicenceTimg()   );
		tCustomAttMapper.insertCustomerAtt(attr1);
		/*流通许可*/
		TCustomerAtt attr2=new TCustomerAtt();
		attr2.settCId(id);
		attr2.setCreateTime(new Date());
		attr2.settEId(AppUserHelper.getCurrentCompanyId(request));
		attr2.setCreatorName(AppUserHelper.getCurrentUserName(request));
		attr2.setDeptName(AppUserHelper.getCurrentDeptName(request));
		attr2.setDeptId(AppUserHelper.getCurrentDeptId(request));
		attr2.setCreatorId(AppUserHelper.getCurrentUserId(request));
		attr2.setType("2");//码表值-营业执照
		attr2.setDeleteFlag("0");
		attr2.setUrl(  tEnterpriseLicence.getLicenceImg2() );
		attr2.settUrl( tEnterpriseLicence.getLicenceTimg2()   );
		tCustomAttMapper.insertCustomerAtt(attr2);
		/*保存区域信息*/
		/*保存区域信息*/
		if(StringUtils.isNotBlank(areaJson)) {
			dealerMapper.deleteArreasByCId(id);
			dealerMapper.insertArreas(json2List(areaJson),id);
		}
		
	}
}
